package net.loyin.app.ctrl.admin;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import net.loyin.app.Constant;
import net.loyin.app.icp.AdminInterceptor;
import net.loyin.app.icp.FrontInterceptor;
import net.loyin.app.model.SysUser;
import net.loyin.utils.encrypt.DESUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by loyin on 16/1/12.
 */
@Clear(FrontInterceptor.class)
@Before(AdminInterceptor.class)
public abstract class AdminBaseCtrl extends Controller{
    public Logger logger= Logger.getLogger(this.getClass());
    public static final String JSON_RESULT_SUCCESS="111";
    public static final String JSON_RESULT_ERROR="000";
    public static final String JSON_RESULT_WARNNING="222";
    public static final String JSON_RESULT_LOGIN_TIMEOUT="001";

    /**
     * 返回json
     * @param code 返回码
     * @param msg 消息
     * @param value 数值
     */
    public void renderJsonMsg(String code,String msg,Object... value){
        Map<String,Object> msgJson=new HashMap<>();
        msgJson.put("code",code);
        if(StringUtils.isNoneBlank(msg))
            msgJson.put("msg",msg);
        if(value!=null)
            msgJson.put("value",value);
        this.renderJson(msgJson);
    }
    public void index(){
        String para=this.getPara();
        if(StringUtils.isNotEmpty(para))
            this.render(para.replaceAll("\\-","/"));
        else{
            String gotoUrl=this.getPara("go");
            if(StringUtils.isNotEmpty(gotoUrl))
                this.render(gotoUrl);
        }
    }
    public void renderJson(Object json){
        this.getResponse().setHeader("Pragma", "no-cache");
        this.getResponse().setHeader("Cache-Control", "no-cache");
        this.getResponse().setDateHeader("Expires", 0);

        String agent = getRequest().getHeader("User-Agent");
        boolean forIE=false;
        if(agent.contains("MSIE")){
            forIE=true;
        }
        this.renderText(JSON.toJSONString(json),forIE ? "text/html; charset=utf-8" : "application/json; charset=utf-8");
    }
    /**
     * 获取angular等请求的json流
     * @return RequestEntity
     */
    public Object getJsonReq(Class clz){
        try{
            HttpServletRequest request=this.getRequest();
            request.setCharacterEncoding("UTF-8");
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader=null;
            try{
                reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
                String line=null;
                while((line = reader.readLine())!=null){
                    buffer.append(line);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
            }
            if(StringUtils.isNotEmpty(buffer)){
                logger.debug("json:\t"+buffer.toString());
                return JSON.parseObject(buffer.toString(),clz);
            }
        }catch(Exception e){
            logger.error(e);
        }
        return null;
    }
    public SysUser getUser(){
        return SysUser.dao.findById(getUserId());
    }
    public String getUserId(){
        String userid=this.getCookie(PropKit.get(Constant.LOGIN_COOKIE_KEY));
        if(StringUtils.isNoneBlank(userid)) {
            try {
                return new DESUtils().decryptString(userid);
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 获取真实IP
     * @return
     */
    public String getRemortIP() {
        HttpServletRequest request=this.getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }
}